<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use Dcat\Admin\Admin;
use Intervention\Image\Facades\Image;
use App\Models\ProjectLayer;
use App\Models\ProjectLayerPoint;
use App\Models\ProjectUser;
use App\Models\Cabinet;
use App\Models\CabinetPoint;

class ProjectLayerController extends Controller
{
    public function index(Content $content, $projectId, $layerId = 0)
    {
        Admin::js('/layui/layui.js');
        Admin::js('/context/context.js');
        Admin::js('/context/drag.js');
        Admin::css('/layui/css/layui.css');
        Admin::css('/context/context.standalone.css');
        Admin::css('/project-layer/css/main.css');

        $background = '';
        if ($layerId) {
            $layer = ProjectLayer::find($layerId);
        } else {
            $layer = ProjectLayer::where('project_id', $projectId)->first();
        }

        $layers = ProjectLayer::where('project_id', $projectId)->get()->toArray();
        $tree = [];
        foreach ($layers as $v) {
            $one['title'] = $v['name'];
            $one['id'] = $v['id'];
            $one['url'] = env('APP_URL').'/admin/project-layer/'.$v['project_id'].'/'.$v['id'];
            array_push($tree, $one);
        }

        $points = [];
        if ($layer) {
            $background = ProjectLayer::getImageUrl($layer['background']);

            $coordinate = Redis::get(ProjectLayer::LAYER_COORDINATE_KEY.$layer->id);
            if ($coordinate) {
                $points = json_decode($coordinate, true);
            } elseif ($layer->coordinate) {
                $points = json_decode($layer->coordinate, true);
            }
        }

        $data = [
            'projectId' => $projectId,
            'layerId' => isset($layer) ? $layer->id : $layerId,
            'background' => $background,
            'points' => $points,
            'tree' => json_encode($tree),
        ];

        return $content
            ->header('项目管理')
            ->description('')
            ->body(view('admin.project-layer.set-layer',$data));
    }

    public function addLayer(Request $request)
    {
        $param = $request->all();

        if (!isset($param['projectId']) || !$param['projectId'] 
            || !isset($param['name']) || !$param['name'] 
            || !isset($param['background']) || !$param['background']
        ) {
            return response()->json(['code' => 0, 'msg' => '信息缺失']);
        }

        try {
            $file = $request->file('background');
            $imageRoot = ProjectLayer::getImageRoot();
            $imageName = md5(uniqid()).'.'.$file->getClientOriginalExtension();
            $path = ProjectLayer::IMAGE_PATH.'/'.$imageName;
            $fullPath = $imageRoot.$path;

            $image = Image::make($file->getRealPath());
            $width = ProjectLayer::IMAGE_WIDTH;
            $height = ProjectLayer::getImageHeight($image->getWidth(), $image->getHeight());
            $image->resize($width, $height);
            $image->save($fullPath);

            $layer = new ProjectLayer();
            $layer->project_id = $param['projectId'];
            $layer->name = $param['name'];
            $layer->background = $path;

            if ($layer->save()) {
                $image = ProjectLayer::getImageUrl($layer['background']);
                $data['background'] = $image;
                $data['url'] = env('APP_URL').'/admin/project-layer/'.$param['projectId'].'/'.$layer->id;
                return response()->json(['code' => 1, 'msg' => '添加成功','data' => $data]);
            } else {
                return response()->json(['code' => 0, 'msg' => '添加失败']);
            }
        } catch (Exception $e) {
            return response()->json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    public function addPoint(Request $request)
    {
        $param = $request->all();

        if (!isset($param['projectId']) || !$param['projectId'] 
            || !isset($param['layerId']) || !$param['layerId'] 
            || !isset($param['pointName']) || !$param['pointName']
        ) {
            return response()->json(['code' => 0, 'msg' => '信息缺失']);
        }

        $point = new ProjectLayerPoint();
        $point->project_id = $param['projectId'];
        $point->layer_id = $param['layerId'];
        $point->type = $param['type'];
        $point->name = $param['pointName'];
        $point->value = $param['pointValue'] ? $param['pointValue'] : 0;
        if ($param['detail']) {
            $cabinetPoint = CabinetPoint::where('alias', $param['detail'])->first();
            $point->cabinet_id = $cabinetPoint['cabinet_id'];
            $point->point_id = $cabinetPoint['id'];
            $point->point_alias = $cabinetPoint['alias'];
        }

        if ($point->save()) {
            return response()->json(['code' => 1, 'msg' => '添加成功', 'data' => $point]);
        } else {
            return response()->json(['code' => 0, 'msg' => '添加失败']);
        }
    }

    public function saveCoordinate(Request $request)
    {
        $param = $request->all();
        $layerId = $param['layerId'];
        $key = ProjectLayer::LAYER_COORDINATE_KEY.$layerId;
        $value = json_encode($param['data']);
        if (Redis::set($key, $value)) {
            //清理库中脏数据
            $dbPoints = ProjectLayerPoint::where('layer_id', $layerId)->pluck('id')->toArray();
            foreach ($param['data'] as $one) {
                $k = array_search($one['id'], $dbPoints);
                if ($k !== false) {
                    unset($dbPoints[$k]);
                }
            }
            ProjectLayerPoint::whereIn('id', $dbPoints)->delete();
            //坐标在库中备一份
            $layer = ProjectLayer::find($layerId);
            $layer->coordinate = $value;
            $layer->save();
            return response()->json(['code' => 1, 'msg' => '保存成功']);
        } else {
            return response()->json(['code' => 0, 'msg' => '保存失败']);
        }
    }

    public function getBoxes(Request $request)
    {
        $boxes = Cabinet::where('pid','0')->get(['id', DB::raw('name as text')]);
        return $boxes;
        return response()->json(['code' => 1, 'msg' => '成功', 'data' => $boxes]);
    }

    public function getCabinets(Request $request)
    {
        $param = $request->all();
        $boxes = Cabinet::where('pid', $param['boxId'])->get(['id', DB::raw('name as text')]);
        return $boxes;
    }

    public function getDetail(Request $request)
    {
        $param = $request->all();
        $detail = CabinetPoint::where('cabinet_id', $param['cabinetId'])->get(['alias', DB::raw('name as text')]);
        return $detail;
    }
}